srvMap.add('queryTouristSourceList','','front/sh/analysis!execute?uid=queryTouristSourceList');
srvMap.add('downloadProvRegionList','','front/sh/export!execute?uid=downloadProvRegionList');
srvMap.add('downloadCityRegionList','','front/sh/export!execute?uid=downloadCityRegionList');
srvMap.add('downloadFornRegionList','','front/sh/export!execute?uid=downloadFornRegionList');
var provBarCharts; //省外游客来源
var cityBarCharts; //省内游客来源
var fornBarCharts; //境外游客来源
var lastQueryParamObj={};	//最近一次查询param--用于查询和下载同条件
var FORN_Rank_Top_NUM=$("#FORN_Rank_Top_NUM").html();
/**
 * 用POST提交解决参数过长
 */
var _postSubmit = function(url, params) {
	var exportForm = document.createElement("FORM");
	document.body.appendChild(exportForm);
	exportForm.method = "POST";

	if (null != params && params.length > 0)
		for ( var i = 0; i < params.length; i++) {
			var param = params[i].split("=");
			var inputElement = document.createElement("input");
			inputElement.setAttribute("name", param[0]);
			inputElement.setAttribute("type", "hidden");
			exportForm.appendChild(inputElement);
			inputElement.value = fromatParam(param);
		}

	exportForm.action = url;
	exportForm.submit();

	document.body.removeChild(exportForm);
};
var fromatParam = function(param) {
	var res = "";
	for (var i = 1; i < param.length; i++) {
		res += param[i];
		if (i < (param.length - 1)) {
			res += "=";
		}
	}
	return res;
};

$(function() {
	
	$(document).ready(function(){
		Util.loadUpInfo.initCityList();
		Util.loadUpInfo.initRegionTypleList();
		Util.loadUpInfo.initRegionList();
		initDataTime();
		//绑定查询事件
		$(".select_button").on("click",function(){
			
			//获取界面参数
			var paramObj = {};
			paramObj = getParamObj(paramObj);
			
			lastQueryParamObj = paramObj;
			queryTouristSourceData(paramObj);
			
		});
		
		
		
		//绑定下载按钮事件
		$("#exportProvData").on("click",function(){
			var paramObj = {};
			paramObj = getParamObj(paramObj);
			downloadProvRegionList(paramObj);
		});
		
		$("#exportCityData").on("click",function(){
			var paramObj = {};
			paramObj = getParamObj(paramObj);
			downloadCityRegionList(paramObj);
		});
		
		$("#exportFornData").on("click",function(){
			var paramObj = {};
			paramObj = getParamObj(paramObj);
			downloadFornRegionList(paramObj);
		});
		
		//查询省内/外游客来源数据---支持从来源分析主界面跳转过来
		lastQueryParamObj.cityId = $("#in_cityId").html();
		lastQueryParamObj.cityName = $("#in_cityName").html();
		lastQueryParamObj.regionTypeName = $("#in_regionTypeName").html();
		lastQueryParamObj.regionId = $("#in_regionId").html();
		lastQueryParamObj.cycleId = $("#in_cycleId").html();
		lastQueryParamObj.startTime = $("#in_startTime").html().replace("-","").replace("-","");
		lastQueryParamObj.endTime = $("#in_endTime").html().replace("-","").replace("-","");
		var regionType = $("#in_regionType").html();
		/*if( lastQueryParamObj.regionId.length == 0 ){
			lastQueryParamObj.regionType = regionType;
		}*/
		lastQueryParamObj.regionType = regionType;
		
		//根据传入参数，还原界面控件输入值
//		if( lastQueryParamObj.cycleId == "day"){
//			$("#dayStart").val($("#in_startTime").html());
//			$("#dayEnd").val($("#in_endTime").html());
//
//		}else{
//			$("#monthStart").val($("#in_startTime").html());
//			$("#monthEnd").val($("#in_endTime").html());
//			
//			$("#monthStart").show();
//			$("#monthEnd").show();
//			$("#dayStart").hide();
//			$("#dayEnd").hide();
//			
//			$('input[name="dataTimeType"]').eq(0).attr("checked","checked");
//		}
		
		//还原传入的参数值到界面上
		if( lastQueryParamObj.cityId.length != 0 ){
			//$("#cityId").val(lastQueryParamObj.cityId);
			$('#citySelect span li').text(decodeURIComponent(lastQueryParamObj.cityName));
			$('#citySelect span li').attr("d_value",lastQueryParamObj.cityId);
			//$('#citySelect span li').attr("d_value",lastQueryParamObj.cityId);
		}
		
		if( regionType.length != 0 ){
			//$("#regionType").val(regionType);
			$('#regionTypleSelect span li').text(decodeURIComponent(lastQueryParamObj.regionTypeName));
		}
		
		if( lastQueryParamObj.regionId.length != 0 ){
			var regionName = $("#in_regionName").html();
			//$("#divselectInput").val(decodeURIComponent(regionName));
			//$("#inputselect").val(lastQueryParamObj.regionId);

			$("#divselectInput").val(decodeURIComponent(regionName));
			$('#inputselect').val(lastQueryParamObj.regionId);
		}
		
		if(lastQueryParamObj.cycleId == 'month'){
			$("#mon_radio").attr("checked","checked");
			$("#day_radio").removeAttr("checked");
			
			$('#dayStartDiv').hide();
			$('#monthStartDiv').show();
			$('#dayEndDiv').hide();
			$('#monthEndDiv').show();
			
			$('#monthStart').val($("#in_startTime").html());
			$('#monthEnd').val($("#in_endTime").html());
		}
		if(lastQueryParamObj.cycleId == 'day'){
			$('#dayStart').val($("#in_startTime").html());
			$('#dayEnd').val($("#in_endTime").html());
		}
		
		//发起查询
		queryTouristSourceData(lastQueryParamObj);
	});
	//绑定日期类型radio切换事件
	$('input[name=dataTimeType]').on("change",function(){
		if( $(this).val() == "day" ){
			$("#dayStartDiv").show();
			$("#dayEndDiv").show();
			//var date=now_Date.format("yyyy-MM-dd"); 
			//$("#dayStart").val(date);
			$("#monthStartDiv").hide();
			$("#monthEndDiv").hide();
		}else{
			
			$("#monthStartDiv").show();
			$("#monthEndDiv").show();
			$("#dayStartDiv").hide();
			$("#dayEndDiv").hide();
		}
	});
});


/**
 * 获取paramObj
 * @param paramObj
 * @returns {Boolean}
 */
function getParamObj(paramObj){
	paramObj.cityId = $('#citySelect span li').attr("d_value")|| "";
	paramObj.regionId = $('#inputselect').val() || "";
	paramObj.regionType = "";
	paramObj.cycleId = $('input[name="dataTimeType"]:checked').val();
	if( paramObj.cycleId == 'day'){
		paramObj.startTime = $('#dayStart').val().replace("-","").replace("-","");
		paramObj.endTime = $('#dayEnd').val().replace("-","").replace("-","");
	}else{
		paramObj.startTime = $('#monthStart').val();
		paramObj.endTime = $('#monthEnd').val();
	}
	
	
	if( paramObj.startTime == null || paramObj.startTime.length == 0 ){
		alert("请选择查询开始时间！");
		return;
	}
	
	if( paramObj.endTime == null || paramObj.endTime.length == 0 ){
		alert("请选择查询结束时间！");
		return;
	}
	
	//如果选择了regionId，则忽略类型参数
	/*if( paramObj.regionId == null || paramObj.regionId.length == 0 ){
		paramObj.regionType = $('#regionType').val();
	}*/
	paramObj.regionType = $('#regionTypleSelect span li').attr("d_value");
	return paramObj;
}

/**
 * 
 * @Description : 查询省内/外游客来源数据
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月11日 下午15:01
 * 
 */
function queryTouristSourceData(paramObj){
	var par = "&cityId="+paramObj.cityId+"&provinceId="+DEPLOY_ANALYSIS_PROVINCE_ID+"&regionId="+paramObj.regionId+"&regionName="+paramObj.regionName+"&regionType="+paramObj.regionType+"&cycleId="+paramObj.cycleId+"&startTime="+paramObj.startTime+"&endTime="+paramObj.endTime;
	Util.ajax.postJsonSync(srvMap.get('queryTouristSourceList'),par,function(json,status){
		if(status){
			if( paramObj == null ){	//初次加载，显示系统出数日期
				var year = json.object.startTime.slice(0,4);
				var month = json.object.startTime.slice(4,6);
				var day = json.object.startTime.slice(6,8);
				var _startTime = year+"-"+month+"-"+day;
				$("#dayStart").val(_startTime);
				
				year = json.object.endTime.slice(0,4);
				month = json.object.endTime.slice(4,6);
				day = json.object.endTime.slice(6,8);
				var _endTime = year+"-"+month+"-"+day;
				$("#dayEnd").val(_endTime);
				
				lastQueryParamObj.startTime = _startTime;
				lastQueryParamObj.endTime = _endTime;
			}
			
			var i = 0;
			var provData = {};
			var axis = [];
			var axisValue = [];
			//渲染省外游客数据
			for( i=0; i<json.object.provList.length; i++ ){
				axis.push(json.object.provList[i].prov_name);
				axisValue.push(json.object.provList[i].vst_person_cnts);
			}
			
			provData.axis = axis;
			provData.axisValue = axisValue;
			buildProvSourceBar(provData);
			
			
			//渲染省内游客数据
			var cityData = {};
			axis = [];
			axisValue = [];
			for( i=0; i<json.object.cityList.length; i++ ){
				axis.push(json.object.cityList[i].city_name);
				axisValue.push(json.object.cityList[i].vst_person_cnts);
			}
			
			cityData.axis = axis;
			cityData.axisValue = axisValue;
			buildCitySourceBar(cityData);
			
			//渲染境外游客数据
			var fornData = {};
			axis = [];
			axisValue = [];
			for( i=0; i<json.object.fornList.length; i++ ){
				if(i==parseInt(FORN_Rank_Top_NUM)){
					break;
				}
				axis.push(json.object.fornList[i].prov_name);
				axisValue.push(json.object.fornList[i].vst_person_cnts);
			}
			
			fornData.axis = axis;
			fornData.axisValue = axisValue;
			buildFornSourceBar(fornData);
		}
		else{
			 alert('查询省内/境/外游客来源数据出错！');   
		}
//	var url = CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.queryTouristSourceList.invoke";
//	Base.ajax({
//		url: url,
//		data:paramObj,
//		success: function(req) {
//			if( paramObj == null ){	//初次加载，显示系统出数日期
//				var year = req.startTime.slice(0,4);
//				var month = req.startTime.slice(4,6);
//				var day = req.startTime.slice(6,8);
//				var _startTime = year+"-"+month+"-"+day;
//				$("#dayStart").val(_startTime);
//				
//				year = req.endTime.slice(0,4);
//				month = req.endTime.slice(4,6);
//				day = req.endTime.slice(6,8);
//				var _endTime = year+"-"+month+"-"+day;
//				$("#dayEnd").val(_endTime);
//				
//				lastQueryParamObj.startTime = _startTime;
//				lastQueryParamObj.endTime = _endTime;
//			}
//			
//			var i = 0;
//			var provData = {};
//			var axis = [];
//			var axisValue = [];
//			//渲染省外游客数据
//			for( i=0; i<req.provList.length; i++ ){
//				axis.push(req.provList[i].prov_name);
//				axisValue.push(req.provList[i].vst_person_cnts);
//			}
//			
//			provData.axis = axis;
//			provData.axisValue = axisValue;
//			buildProvSourceBar(provData);
//			
//			
//			//渲染省内游客数据
//			var cityData = {};
//			axis = [];
//			axisValue = [];
//			for( i=0; i<req.cityList.length; i++ ){
//				axis.push(req.cityList[i].city_name);
//				axisValue.push(req.cityList[i].vst_person_cnts);
//			}
//			
//			cityData.axis = axis;
//			cityData.axisValue = axisValue;
//			buildCitySourceBar(cityData);
//		}
	});
}



/**
 * 
 * @Description : 渲染省外游客来源柱状图
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年11月17日 下午16:01
 * 
 */
function buildProvSourceBar(resultData) {
	
	hideLoading(provBarCharts);
	
	if ( resultData.isEmpty == 1 ) {
		noDataShowSource(provBarCharts, 'provBarChartsDiv');
		
		//无数据时，禁用下载按钮
		$("#exportProvData").attr("disabled","disabled");
		return;
	}
	
	$("#exportProvData").removeAttr("disabled");
	
	//展示前10的数据
	//var axis = resultData.axis.slice(0,10);
	//var axisValue = resultData.axisValue.slice(0,10);
	var axis = resultData.axis;
	var axisValue = resultData.axisValue;
	require.config({
		paths: {
			echarts: CONTENT_PATH + '/common/js'
		}
	});
	require(
		[
			'echarts',
			'echarts/chart/bar'
		],
		function(ec) {
			option = {
				title: {
					text: '省外游客来访人数',
					x: 'center'
				},
				tooltip: {
					trigger: 'item',
					textStyle : {
						align : 'left'
					},
					formatter: function(params) {
						return params.name + ':</br>' + params.value + '人数';
					}
				},
				calculable: true,
				xAxis: [{
					type: 'category',
					show: true,
					data: axis
				}],
				yAxis: [{
					name: "人数",
					type: 'value',
					show: true
				}],
				series: [{
					type: 'bar',
					barWidth: 20,
					itemStyle: {
						normal: {
							label: {
								show: true,
								position: 'top',
								formatter: '{c}'
							}
						}
					},
					data: axisValue
				}]
			};

			provBarCharts = ec.init(document.getElementById('provBarChartsDiv'),'macarons');
			provBarCharts.clear();
			provBarCharts.setOption(option); 
		}
	);
}

/**
 * 
 * @Description : 渲染省内游客来源柱图
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月11日 下午16:31
 * 
 */
function buildCitySourceBar(resultData) {
	
	hideLoading(cityBarCharts);
	
	if ( resultData.isEmpty == 1 ) {
		noDataShowSource(cityBarCharts, 'cityBarChartsDiv');
		
		//无数据时，禁用下载按钮
		$("#exportCityData").attr("disabled","disabled");
		return;
	}

	$("#exportCityData").removeAttr("disabled");
	
	require.config({
		paths: {
			echarts: CONTENT_PATH + '/common/js'
		}
	});
	require(
		[
			'echarts',
			'echarts/chart/bar'
		],
		function(ec) {
			option = {
				title: {
					text: '省内游客来访人数',
					x: 'center'
				},
				tooltip: {
					trigger: 'item',
					textStyle : {
						align : 'left'
					},
					formatter: function(params) {
						return params.name + ':</br>' + params.value + '人数';
					}
				},
				calculable: true,
				xAxis: [{
					type: 'category',
					show: true,
					data: resultData.axis
				}],
				yAxis: [{
					name: "人数",
					type: 'value',
					show: true
				}],
				series: [{
					type: 'bar',
					barWidth: 40,
					itemStyle: {
						normal: {
							label: {
								show: true,
								position: 'top',
								formatter: '{c}'
							}
						}
					},
					data: resultData.axisValue
				}]
			};

			cityBarCharts = ec.init(document.getElementById('cityBarChartsDiv'),'macarons');
			cityBarCharts.clear();
			cityBarCharts.setOption(option);
		}
	);
}

/**
 * 
 * @Description : 渲染境外游客来源柱图
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月11日 下午16:31
 * 
 */
function buildFornSourceBar(resultData) {
	
	hideLoading(fornBarCharts);
	
	if ( resultData.isEmpty == 1 ) {
		noDataShowSource(fornBarCharts, 'fornBarChartsDiv');
		
		//无数据时，禁用下载按钮
		$("#exportFornData").attr("disabled","disabled");
		return;
	}

	$("#exportFornData").removeAttr("disabled");
	
	require.config({
		paths: {
			echarts: CONTENT_PATH + '/common/js'
		}
	});
	require(
		[
			'echarts',
			'echarts/chart/bar'
		],
		function(ec) {
			option = {
				title: {
					text: '境外游客来访人数',
					x: 'center'
				},
				tooltip: {
					trigger: 'item',
					textStyle : {
						align : 'left'
					},
					formatter: function(params) {
						return params.name + ':</br>' + params.value + '人数';
					}
				},
				calculable: true,
				xAxis: [{
					type: 'category',
					show: true,
					data: resultData.axis,
					axisLabel : {
						margin : 5,
						rotate : 45,
						textStyle : {
							align : 'left'
						}
					}
				}],
				yAxis: [{
					name: "人数",
					type: 'value',
					show: true
				}],
				series: [{
					type: 'bar',
					barWidth: 20,
					itemStyle: {
						normal: {
							label: {
								show: true,
								position: 'top',
								formatter: '{c}'
							}
						}
					},
					data: resultData.axisValue
				}]
			};

			fornBarCharts = ec.init(document.getElementById('fornBarChartsDiv'),'macarons');
			fornBarCharts.clear();
			fornBarCharts.setOption(option);
		}
	);
}

/**
 * 下载全国各省客流信息
 */
function downloadProvRegionList(paramObj) {
	var par = "&cityId="+paramObj.cityId+"&provinceId="+DEPLOY_ANALYSIS_PROVINCE_ID+"&regionId="+paramObj.regionId+"&regionName="+paramObj.regionName+"&regionType="+paramObj.regionType+"&cycleId="+paramObj.cycleId+"&startTime="+paramObj.startTime+"&endTime="+paramObj.endTime;
	var url = srvMap.get('downloadProvRegionList');
	_postSubmit(url, par.split("&"));
	return;
//	var str = getParamsStr();
//
//	window.open(CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.downloadProvRegionList.invoke?" + str, '_blank');
}

/**
 * 下载全省各市客流信息
 */
function downloadCityRegionList(paramObj) {
	var par = "&cityId="+paramObj.cityId+"&provinceId="+DEPLOY_ANALYSIS_PROVINCE_ID+"&regionId="+paramObj.regionId+"&regionName="+paramObj.regionName+"&regionType="+paramObj.regionType+"&cycleId="+paramObj.cycleId+"&startTime="+paramObj.startTime+"&endTime="+paramObj.endTime;
	var url = srvMap.get('downloadCityRegionList');
	_postSubmit(url, par.split("&"));
	return;
//	var str = getParamsStr();
//
//	window.open(CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.downloadCityRegionList.invoke?" + str, '_blank');
}

/**
 * 下载境外客流信息
 */
function downloadFornRegionList(paramObj) {
	var par = "&cityId="+paramObj.cityId+"&provinceId="+DEPLOY_ANALYSIS_PROVINCE_ID+"&regionId="+paramObj.regionId+"&regionName="+paramObj.regionName+"&regionType="+paramObj.regionType+"&cycleId="+paramObj.cycleId+"&startTime="+paramObj.startTime+"&endTime="+paramObj.endTime;
	var url = srvMap.get('downloadFornRegionList');
	_postSubmit(url, par.split("&"));
	return;
}


/**
 * 获取页面参数
 * @returns {String}
 */
function getParamsStr() {
	
	//编码加密
	cityId = encodeURIComponent(lastQueryParamObj.cityId).EncodeBase64();
	regionType = encodeURIComponent(lastQueryParamObj.regionType).EncodeBase64();
	regionId = encodeURIComponent(lastQueryParamObj.regionId).EncodeBase64();
	cycleId = encodeURIComponent(lastQueryParamObj.cycleId).EncodeBase64();
	startTime = encodeURIComponent(lastQueryParamObj.startTime).EncodeBase64();
	endTime = encodeURIComponent(lastQueryParamObj.endTime).EncodeBase64();
	
	var str = "";
	str += 'cityId=' + cityId;
	str += '&regionId=' + regionId;
	str += '&regionType=' + regionType;
	str += '&cycleId=' + cycleId;
	str += '&startTime=' + startTime;
	str += '&endTime=' + endTime;
	

	return str;
}


/**
 * 
 * @Description : 初始化时间控件
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月10日 下午10:05
 * 
 */
function initDataTime() {
	var dayStart = {
		elem: '#dayStart',
		format: 'YYYY-MM-DD',
		start: laydate.now(-183),
		min: laydate.now(-183),
		max: laydate.now(-1), //最大日期
		istime: false,
		festival: true,
		istoday: true,
		choose: function(datas){
			dayEnd.min = datas; //开始日选好后，重置结束日的最小日期
			dayEnd.start = datas //将结束日的初始值设定为开始日
	    }
	};
	
	var dayEnd = {
		elem: '#dayEnd',
		format: 'YYYY-MM-DD',
		min: laydate.now(-183),
		max: laydate.now(-1), //最大日期
		istime: false,
		festival: true,
		istoday: true,
		choose: function(datas){
			dayStart.max = datas; //结束日选好后，重置开始日的最大日期
	    }
	};
	
	var preMonth = getPreMonth(laydate.now());
	var preYear = laydate.now(-365).slice(0,7);
	var monthStart = {
		elem: '#monthStart',
		format: 'YYYY-MM',
		start:preMonth,
		min: preYear,
		max:preMonth,
		istime: false,
		festival: true,
		istoday: false,
		choose: function(datas){
			monthEnd.min = datas; //开始日选好后，重置结束日的最小日期
			monthEnd.start = datas //将结束日的初始值设定为开始日
	    }
	};
		
	var monthEnd = {
		elem: '#monthEnd',
		format: 'YYYY-MM',
		start:preMonth,
		min: preYear,
		max:preMonth,
		istime: false,
		festival: true,
		istoday: false,
		choose: function(datas){
			monthStart.max = datas; //结束日选好后，重置开始日的最大日期
	    }
	};
	
	laydate(dayStart);
	laydate(dayEnd);
	
	laydate(monthStart);
	laydate(monthEnd);
	
	//默认展示前12个月的数据
	$("#monthStart").val(preYear.slice(0,7));
	$("#monthEnd").val(preMonth.slice(0,7));
}


/**
 * 
 * @Description : echarts图表数据为空提示
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月10日 下午10:05
 * 
 */
function noDataShowSource(chart,id) {
	
	if (chart == null) {
		require.config({
			paths: {
				echarts: CONTENT_PATH + '/common/js'
			}
		});
		require(['echarts'], function(ec) {
			chart = ec.init(document.getElementById(id), 'macarons');
			chart.clear();
			showEmptyTip(chart);
		});
	} else {
		showEmptyTip(chart);
	}
}

/**
 * 
 * @Description : echarts图表数据为空提示
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月10日 下午10:05
 * 
 */
function showEmptyTip(chart) {
	chart.clear();
	if (chart != null) {
		chart.showLoading({
			text: '当前未查询到数据，请稍后再试',
			effect: 'bubble',
			textStyle: {
				fontSize: 22
			}
		});
	}
}
/**
 * 获取当前时间上一个月日期
 * @Description : 
 * 
 * @return void
 *
 * @author : xuxiong
 * @date : 2015年12月18日 下午5:40:08 
 *
 */
function getPreMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}
/**
 * 
 * @Description : echarts图表过滤动画隐藏
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月10日 下午10:05
 * 
 */
function hideLoading(chart) {
	if (chart != null) {
		chart.hideLoading();
	}
	
	
}